
package com.ifcar.app.activity.picture;

import com.ifcar.app.activity.ImageSwitcherActivity;
import com.ifcar.app.activity.HomePage;
import com.ifcar.app.bean.PhotosetListInfo;
import com.ifcar.app.fragment.NRPullLoadingListFrament;
import com.ifcar.app.model.News;
import com.ifcar.app.model.PictureSet;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.util.BaseImageDownloader;
import com.ifcar.app.util.PictureGridAdapter;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.view.LoadingListView;
import com.ifcar.app.activity.R;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Message;
import android.text.GetChars;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图集最小控制单元
 * @author zhangyp
 *
 */
public class PictureSetFragment extends NRPullLoadingListFrament implements OnClickListener, OnItemClickListener, OnTouchListener {

    private BaseImageDownloader mImageDownloader;

    private PictureGridAdapter mAdapter;

    private List<PhotosetListInfo> mData;
    
    private int mTouchUpX;
    
    public static final String COLUMN_ID = "columnId";

    public static final String COLUMN_CHANNLE = "columnChannel";

    public static final String COLUMN_NAME = "columnName";
    
    String mColumnID;

    String mColumnChannel;

    String mColumnName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Bundle bundle = getArguments();
        if (bundle != null) {
            mColumnID = bundle.getString(COLUMN_ID);
            mColumnChannel = bundle.getString(COLUMN_CHANNLE);
            mColumnName = bundle.getString(COLUMN_NAME);
        }else{
            mColumnID = PictureSet.Main_Photo_Column;
            mColumnChannel = PictureSet.Normal_Channle;
            mColumnName = "图集";
        }
        
        setRefreshTag(mColumnID);
        setLoadingNum(10);
    }

    @Override
    public void onLoadingListViewAttached(LoadingListView loadingListView) {
        super.onLoadingListViewAttached(loadingListView);
        loadingListView.getListView().setOnTouchListener(this);
        loadingListView.getListView().setOnItemClickListener(this);
        Button button = getMoreButton();
        button.setBackgroundResource(R.drawable.photoset_netease_big_button);
        button.setTextColor(getResources().getColor(R.color.night_list_title_color));
    }

    @Override
    public void onLoadingListViewDetached(LoadingListView loadingListView) {
        super.onLoadingListViewDetached(loadingListView);
        loadingListView.getListView().setOnTouchListener(null);
        loadingListView.getListView().setOnItemClickListener(null);
    }

    @Override
	public ListAdapter getAdapter() {
		return mAdapter;
	}

    @Override
    public void onTabSelected(boolean first) {
        super.onTabSelected(first);

        if (first) {
            startLoading();
        }

        if (mImageDownloader != null) {
            mImageDownloader.setThread(Thread.currentThread());
        }

        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onTabUnSelected() {
        super.onTabUnSelected();

        if (mImageDownloader != null) {
            mImageDownloader.setThread(null);
        }

        ListView listView = getListView();
        if (listView != null) {
            final int count = listView.getChildCount();
            for (int i = 0; i < count; i++) {
                View child = listView.getChildAt(i);
                View item1 = child.findViewById(R.id.picture_item1);
                View item2 = child.findViewById(R.id.picture_item2);
                
                clearItemViewBitmap(item1);
                clearItemViewBitmap(item2);
            }
        }
    }
    
    private void clearItemViewBitmap(View item) {
        if (item == null) {
            return;
        }

        ImageView imageView = (ImageView) item.findViewById(R.id.photosetitemimage);

        if (imageView != null) {
            imageView.setImageDrawable(null);
        }
    }

    @Override
    protected void onLoading() {
        super.onLoading();
        // 加载本地数据,没有启用新线程
        List<PhotosetListInfo> list = PictureSet.getPhotosListFromDB(getDb(),mColumnID);
        Message msg = getHandler().obtainMessage(MSG_LOADING);
        msg.obj = list;
        getHandler().dispatchMessage(msg);
    }

    @Override
    protected void onHandleLoading(Object result) {
        super.onHandleLoading(result);

        List<PhotosetListInfo> list = (List<PhotosetListInfo>) result;
              
        if (list != null && list.size() > 0) {
            callLoadingListViewAddMoreView();
        }
        
        setData(list);

        // 当本地有数据的情况下延时200ms再刷新,如果马上刷新在网速较快的情况下可能造成tab界面切换时卡
        if (mAdapter != null && mAdapter.getCount() > 0) {
            if (isNeedRefresh()) {
                getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refresh();
                    }
                }, 200);
            }
        } else {
            refresh();
        }
    }

    @Override
    protected void onRefreshing() {
        super.onRefreshing();
        callLoadingListViewStartLoading(mAdapter == null);
        String setId = null;
        if (mData != null && mData.size() > 0) {
            PhotosetListInfo info = mData.get(0);
            if (info != null) {
                setId = info.getSetid();
            }
        }
        final String maxSetId = setId;
        final Context context = getActivity();
        final SQLiteDatabase sqldb = getDb();
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<PhotosetListInfo> list = PictureSet.getPhotosList(context, sqldb, maxSetId,mColumnID,mColumnChannel);
                Message msg = getHandler().obtainMessage(MSG_REFRESHING);
                msg.obj = list;
                getHandler().sendMessage(msg);
            }
        }).start();
    }

    @Override
    protected void onHandleRefreshing(Object result) {
        super.onHandleRefreshing(result);
        List<PhotosetListInfo> data = (List<PhotosetListInfo>) result;
        
        if (data != null && data.size() > 0) {
            callLoadingListViewAddMoreView();
        } else if (mAdapter == null || mAdapter.getCount() == 0) {
            callLoadingListViewRemoveMoreView();
        }

        if (data == null) {
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoading(false, true);
        } else if(data.size()==0){
            Toast.makeText(getActivity(), R.string.msg_loading_nodata, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoading(false, true);
        }else {
            callLoadingListViewCompleteLoading(true, true);
            setData(data);
        }
    }

    @Override
    protected void onLoadingMore() {
        super.onLoadingMore();
        final int num = getLoadingNum();
        final int start = (mData == null || mData.size() == 0) ? 0 : getLoadingStart() + num;
        callLoadingListViewStartLoadingMore(start);

        final String minSetId = (mData == null || mData.size() == 0) ? null : mData.get(
                mData.size() - 1).getSetid();
        final Context context = getActivity();
        // 取网络
        new Thread(new Runnable() {
            @Override
            public void run() {

                List<PhotosetListInfo> list = PictureSet.getPhotosListMore(context, minSetId,mColumnID,mColumnChannel);
                Message msg = getHandler().obtainMessage(MSG_LOADING_MORE);
                msg.obj = list;
                getHandler().sendMessage(msg);
            }
        }).start();
    }

    @Override
    protected void onHandleLoadingMore(Object result) {
        super.onHandleLoadingMore(result);
        List<PhotosetListInfo> data = (List<PhotosetListInfo>) result;
        if (data == null) {
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoadingMore(false, true);
        } else if(data.size()==0) {
            Toast.makeText(getActivity(), R.string.msg_loading_nomore, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoadingMore(true, false);
        }else{
            callLoadingListViewCompleteLoadingMore(true, true);
            addData(data);
        }
    }

    private void setData(List<PhotosetListInfo> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        String maxSetId = null;
        if (mData != null && mData.size() > 0) {
            PhotosetListInfo info = mData.get(0);
            if (info != null) {
                maxSetId = info.getSetid();
            }
        }

        if (TextUtils.isEmpty(maxSetId)) {
            mData = data;
        } else {
            PhotosetListInfo info = data.get(data.size() - 1);
            if (info != null && maxSetId.equals(info.getSetid())) {
                // 没有断层,最后一条数据应该是一样的,所以删除
                data.remove(data.size() - 1);

                if (data.size() > 0) {
                    // 再加上现有数据
                    data.addAll(mData);
                    mData = data;
                }
            } else {
                mData = data;
            }
        }

        // 只显示10条,删除多余数据
        if (mData.size() > 10) {
            List<PhotosetListInfo> subData = new ArrayList<PhotosetListInfo>();
            subData.addAll(mData.subList(10, mData.size()));
            mData.removeAll(subData);
        }

        if (mImageDownloader == null) {
            mImageDownloader = new BaseImageDownloader(getActivity(), null);
            mImageDownloader.setMode(BaseImageDownloader.Mode.CORRECT);
            mImageDownloader.setThread(Thread.currentThread());
        }

        mAdapter = new PictureGridAdapter(getActivity(), mData, mImageDownloader, this);
        if(null!=getListView()){
            getListView().setAdapter(mAdapter);
        }
        
    }

    private void addData(List<PhotosetListInfo> data) {
        if (data == null || data.size() == 0 || mData == null) {
            return;
        }
        mData.addAll(data);
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }
    
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            mTouchUpX = (int)event.getX();
        }
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long itemId) {
        ListView listView = getListView();
        if (mTouchUpX < 0 || listView == null || mAdapter == null
                || mAdapter.getCount() <= position) {
            return;
        }
        position -= listView.getHeaderViewsCount();
        if (position < 0) {
            return;
        }
        
        PhotosetListInfo[] infos = mAdapter.getItem(position);
        if (infos == null) {
            return;
        }
        
        PhotosetListInfo info = null;
        if (mTouchUpX > adapterView.getWidth() / 2) {
            info = infos.length > 1 ? infos[1] : null;
        } else {
            info = infos.length > 0 ? infos[0] : null;
        }
        
        if (info == null) {
            return;
        }
        
        String setid = info.getSetid();
        String imgsum = info.getImgsum();
        String imgTitle = info.getSetname();
        String clientcover = info.getClientcover();

        Intent intent = new Intent(getActivity(), ImageSwitcherActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("setid", setid);
        bundle.putString("channel", mColumnChannel);
        bundle.putString("imgsum", imgsum);
        bundle.putString("imgTitle", imgTitle);
        bundle.putString("clientcover", clientcover);
        intent.putExtras(bundle);
        startActivity(intent);
        
    }
    
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.picture_item1:
            case R.id.picture_item2: {
                PhotosetListInfo photosetlistinfo = (PhotosetListInfo) v.getTag();
                if (photosetlistinfo == null) {
                    return;
                }

                String setid = photosetlistinfo.getSetid();
                String imgsum = photosetlistinfo.getImgsum();
                String imgTitle = photosetlistinfo.getSetname();
                String clientcover = photosetlistinfo.getClientcover();

                Intent intent = new Intent(getActivity(), ImageSwitcherActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("setid", setid);
                bundle.putString("channel", mColumnChannel);
                bundle.putString("imgsum", imgsum);
                bundle.putString("imgTitle", imgTitle);
                bundle.putString("clientcover", clientcover);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            }

            default:
                break;
        }

    }

    @Override
    public void onApplyTheme() {
    }
}
